package com.yupi.yuaiagent.App;

import com.yupi.yuaiagent.advisor.LoveAppRagCustomAdvisorFactory;
import com.yupi.yuaiagent.advisor.MyLoggerAdvisor;
import com.yupi.yuaiagent.advisor.ReReadingAdvisor;
import com.yupi.yuaiagent.chatmemory.FileBasedChatMemory;
import com.yupi.yuaiagent.chatmemory.MySqlChatMemory;
import com.yupi.yuaiagent.chatmemory.RedisChatMemory;
import com.yupi.yuaiagent.rag.LoveAppVectorStoreConfig;
import com.yupi.yuaiagent.rag.PgVectorVectorStoreConfig;
import com.yupi.yuaiagent.rag.QueryRewriter;
import com.yupi.yuaiagent.service.AiChatMessageService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.util.List;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@Slf4j
@Component
public class LoveApp {

//    @Resource
//    private AiChatMessageService aiChatMessageService;

    private final ChatClient chatClient;

    private static final String SYSTEM_PROMPT = "扮演深耕恋爱心理领域的专家。开场向用户表明身份，告知用户可倾诉恋爱难题。" +
            "围绕单身、恋爱、已婚三种状态提问：单身状态询问社交圈拓展及追求心仪对象的困扰；" +
            "恋爱状态询问沟通、习惯差异引发的矛盾；已婚状态询问家庭责任与亲属关系处理的问题。" +
            "引导用户详述事情经过、对方反应及自身想法，以便给出专属解决方案。";

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 初始化对话模型
     * @param dashscopeChatModel Spring自动注入聊天大模型
     */
    public LoveApp(ChatModel dashscopeChatModel,AiChatMessageService aiChatMessageService,RedisTemplate<String, Object> redisTemplate) {
        // 基于MySQL的持久化会话记忆存储
//        MySqlChatMemory chatMemory = new MySqlChatMemory(aiChatMessageService);
        // 基于文件的会话记忆存储
//        String dir = System.getProperty("user.dir") + "/chat-memory";
//        FileBasedChatMemory chatmemory = new FileBasedChatMemory(dir);
        // 初始化基于内存的对话记忆
        InMemoryChatMemory chatMemory = new InMemoryChatMemory();
        // 基于Redis的内存会话记忆
//        RedisChatMemory chatMemory = new RedisChatMemory(redisTemplate);
        this.chatClient = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(SYSTEM_PROMPT)
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(chatMemory),
                        new MyLoggerAdvisor()            // 自定义日志拦截器
//                        new ReReadingAdvisor()            // 自定义重读拦截器 耗Token
                )
                .build();
    }

    /**
     * AI基础对话 （支持多轮会话记忆）
     * @param message
     * @param chatId
     * @return
     */
    public String doChat(String message,String chatId) {
        ChatResponse chatResponse = chatClient.prompt()
                .user(message)
                .advisors(advisorSpec -> advisorSpec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId) // 取出对应会话id的历史记录
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))                               // 限制会话id当前最多上下文
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }


    /**
     * AI基础对话 （支持多轮会话记忆）
     * @param message
     * @param chatId
     * @return
     */
    public Flux<String> doChatWithStream(String message, String chatId) {
        Flux<String> content = chatClient.prompt()
                .user(message)
                .advisors(advisorSpec -> advisorSpec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId) // 取出对应会话id的历史记录
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))                               // 限制会话id当前最多上下文
                .stream()
                .content();
        log.info("content: {}", content);
        return content;
    }



    // JDK21 新特性 快速定义类包含里面的属性
    public record LoveReport(String title, List<String> Suggestions) {
    }

    /**
     * AI生成恋爱报告 结构化输出
     * @param message
     * @param chatId
     * @return
     */
    public LoveReport doChatWithReport(String message,String chatId) {
//        new ChatMemory()
        LoveReport loveReport = chatClient.prompt()
                .user(message)
                .advisors(advisorSpec -> advisorSpec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId) // 取出对应会话id的历史记录
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))                               // 限制会话id当前最多上下文
                .call()
                .entity(LoveReport.class);
        log.info("LoveReport: {}", loveReport);
        return loveReport;
    }

    @Resource
    private VectorStore loveAppVectorStore;
    @Resource
    private Advisor loveAppRagCloudAdvisor;
//    @Resource
//    private VectorStore pgVectorVectorStore;
    @Resource
    private QueryRewriter queryRewriter;
    /**
     * 基于 RAG 检索增强生成 的恋爱问答
     * @param message
     * @param chatId
     * @return
     */
    public String doChatWithRag(String message,String chatId){
        // 查询重写
//        String rewriteMsg = queryRewriter.doQueryRewrite(message);

        ChatResponse chatResponse = chatClient.prompt()
                .user(message)
                .advisors(advisorSpec -> advisorSpec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId) // 取出对应会话id的历史记录)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))          // 取出当前会话上下文关联的历史记录10条
//                .advisors(
//                        // 自定义日志打印 便于调试
//                        new MyLoggerAdvisor(),
//                        // 应用本地知识库问答
////                        new QuestionAnswerAdvisor(loveAppVectorStore),
//                        // 应用云知识库问答
////                        loveAppRagCloudAdvisor,
//                        // 应用 RAG 增强检索服务 基于PgVector向量数据库存储
//                        new QuestionAnswerAdvisor(pgVectorVectorStore))
////                        )
                .advisors(new MyLoggerAdvisor()
//                        new QuestionAnswerAdvisor(loveAppVectorStore),
//                        LoveAppRagCustomAdvisorFactory.createLoveAppRagCustomAdvisor(loveAppVectorStore, "已婚")
                )
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
//        log.info("content: {}", content);
        return content;
    }


    // 注入工具
    @Resource
    private ToolCallback[] allTools;

    /**
     * 使用注册的工具
     * @param message 提问内容
     * @param chatId 会话id
     * @return
     */
    public String doChatWithTools(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
                .advisors(new MyLoggerAdvisor())
                .tools(allTools)
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
//        log.info("content: {}", content);
        return content;
    }

    @Resource
    private ToolCallbackProvider toolCallbackProvider;

    /**
     * 使用MCP工具
     * @param message 提问内容
     * @param chatId 会话id
     * @return
     */
    public String doChatWithMCP(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
                .advisors(new MyLoggerAdvisor())
                .tools(toolCallbackProvider)
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
//        log.info("content: {}", content);
        return content;
    }


}

